package pers.mihao.quickstream.common.plus.lock.isolated;

import pers.mihao.quickstream.common.plus.lock.GlobalLock;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author mihao
 * @since 2024/11/24
 */
public class JvmGlobalLock implements GlobalLock {

    Map<String, Lock> lockMap = new ConcurrentHashMap<>();

    @Override
    public boolean tryLock(String key) {
        Lock lock = lockMap.computeIfAbsent(key, k -> new ReentrantLock());
        return lock.tryLock();
    }

    @Override
    public void unlock(String key) {
        Lock lock = lockMap.computeIfAbsent(key, k -> new ReentrantLock());
        lock.unlock();
    }
}
